<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="专家库管理">
        管理专家库信息，包括专家池配置、用户授权、管理员限制等。
      </n-card>
    </div>
    <n-card :bordered="false" title="专家库列表" class="mt-4">
      <n-space vertical :size="16">
        <!-- 搜索栏 -->
        <n-space justify="space-between">
          <n-space>
            <n-input
              v-model:value="searchParams.keyword"
              placeholder="请输入专家库名称或描述"
              style="width: 300px"
              clearable
            />
            <n-select
              v-model:value="searchParams.status"
              placeholder="状态筛选"
              :options="statusOptions"
              style="width: 150px"
              clearable
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
            新增专家库
          </n-button>
        </n-space>

        <!-- 数据表格 -->
        <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-key="rowKey"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal
      v-model:show="showModal"
      :title="modalTitle"
      preset="card"
      style="width: 600px"
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        :label-width="100"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="专家库名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入专家库名称" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-space>
              <n-radio :value="1">启用</n-radio>
              <n-radio :value="0">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="管理员限制" path="adminLimit">
          <n-input-number
            v-model:value="formData.adminLimit"
            placeholder="请输入管理员数量限制"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input
            v-model:value="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 用户授权弹窗 -->
    <n-modal
      v-model:show="showAuthModal"
      title="用户授权管理"
      preset="card"
      style="width: 800px"
      :mask-closable="false"
    >
      <n-space vertical :size="16">
        <n-space justify="space-between">
          <n-input
            v-model:value="userSearchKeyword"
            placeholder="搜索用户姓名或唯一标识"
            style="width: 300px"
            clearable
          />
          <n-button type="primary" @click="handleAddUser">
            <template #icon>
              <n-icon>
                <PersonAddOutline />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </n-space>
        <n-data-table
          :columns="userColumns"
          :data="userTableData"
          :loading="userLoading"
          :pagination="userPagination"
          :row-key="rowKey"
        />
      </n-space>
    </n-modal>

    <!-- 添加用户弹窗 -->
    <n-modal
      v-model:show="showAddUserModal"
      title="添加用户"
      preset="card"
      style="width: 500px"
      :mask-closable="false"
    >
      <n-space vertical :size="16">
        <n-form-item label="统一认证号" required>
          <n-select
            v-model:value="selectedUser"
            :options="userSearchResults"
            placeholder="请输入统一认证号搜索"
            filterable
            clearable
            :loading="userSearchLoading"
            remote
            :filter="handleUserSearch"
            @search="handleUserSearch"
          />
        </n-form-item>
        <n-form-item label="用户角色" required>
          <n-radio-group v-model:value="selectedUserRole">
            <n-space>
              <n-radio value="管理员">管理员</n-radio>
              <n-radio value="普通用户">普通用户</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-space>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showAddUserModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :disabled="!selectedUser || !selectedUserRole"
            @click="handleConfirmAddUser"
          >
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog, NSwitch } from 'naive-ui';
import {
  SearchOutline,
  AddOutline,
  CreateOutline,
  TrashOutline,
  PersonOutline,
  PersonAddOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

const message = useMessage();
const dialog = useDialog();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: null as number | null,
});

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

// 表格数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 0,
  onChange: (page: number) => {
    pagination.page = page;
    loadData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    loadData();
  },
});

// 表格列定义
const columns = computed(() => [
  createIndexColumn({
    currentPage: pagination.page,
    pageSize: pagination.pageSize,
  }),
  { title: '专家库名称', key: 'name', width: 200 },
  { 
    title: '状态', 
    key: 'status', 
    width: 100,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h(NSwitch, {
          value: row.status === 1,
          onUpdateValue: (value: boolean) => {
            // 更新数据中的状态
            row.status = value ? 1 : 0;
            console.log('状态切换:', row.id, value ? 1 : 0);
          }
        }),
        h('span', { style: 'font-size: 12px;' }, row.status === 1 ? '启用' : '禁用')
      ]);
    }
  },
  { title: '管理员限制', key: 'adminLimit', width: 120 },
  { title: '创建时间', key: 'createTime', width: 180 },
  { title: '备注', key: 'remark', width: 200 },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row: any) => {
      return h('div', [
        h(
          'n-button',
          {
            size: 'small',
            type: 'primary',
            ghost: true,
            onClick: () => handleEdit(row),
            style: 'margin-right: 8px',
          },
          { default: () => '编辑' }
        ),
        h(
          'n-button',
          {
            size: 'small',
            type: 'info',
            ghost: true,
            onClick: () => handleAuth(row),
            style: 'margin-right: 8px',
          },
          { default: () => '授权' }
        ),
        h(
          'n-button',
          {
            size: 'small',
            type: 'error',
            ghost: true,
            onClick: () => handleDelete(row),
          },
          { default: () => '删除' }
        ),
      ]);
    },
  },
]);

// 表单相关
const showModal = ref(false);
const modalTitle = ref('新增专家库');
const submitLoading = ref(false);
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  status: 1,
  adminLimit: 5,
  remark: '',
});

const rules = {
  name: {
    required: true,
    message: '请输入专家库名称',
    trigger: 'blur',
  },
};

// 用户授权相关
const showAuthModal = ref(false);
const currentPool = ref<any>(null);
const userSearchKeyword = ref('');
const userLoading = ref(false);
const userTableData = ref<any[]>([]);

const userPagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 0,
});

// 添加用户相关
const showAddUserModal = ref(false);
const userSearchResults = ref<any[]>([]);
const selectedUser = ref<any>(null);
const selectedUserRole = ref<string>('');
const userSearchLoading = ref(false);

const userColumns = computed(() => [
  createIndexColumn({
    currentPage: userPagination.page,
    pageSize: userPagination.pageSize,
  }),
  { title: '用户姓名', key: 'name', width: 100 },
  { title: '唯一标识', key: 'employeeId', width: 100 },
  { title: '角色', key: 'department', width: 100 },
  { title: '授权时间', key: 'authTime', width: 140 },
  { title: '状态', key: 'status', width: 80 },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    render: (row: any) => {
      return h(
        'n-button',
        {
          size: 'small',
          type: 'error',
          ghost: true,
          onClick: () => handleRemoveUser(row),
        },
        { default: () => '删除' }
      );
    },
  },
]);



// 方法
const rowKey = (row: any) => row.id;

const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        name: '计算机科学专家库',
        description: '计算机科学领域的专家资源库',
        status: 1,
        adminLimit: 5,
        createTime: '2024-01-15 10:30:00',
        remark: '主要包含软件工程、人工智能等方向专家',
      },
      {
        id: '2',
        name: '医学专家库',
        description: '医学领域的专家资源库',
        status: 1,
        adminLimit: 3,
        createTime: '2024-01-10 14:20:00',
        remark: '包含临床医学、基础医学等专家',
      },
    ];
    pagination.pageCount = 1;
    loading.value = false;
  }, 500);
};

const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

const handleReset = () => {
  searchParams.keyword = '';
  searchParams.status = null;
  pagination.page = 1;
  loadData();
};

const handlePageChange = (page: number) => {
  pagination.page = page;
  loadData();
};

const handleAdd = () => {
  modalTitle.value = '新增专家库';
  Object.assign(formData, {
    id: '',
    name: '',
    status: 1,
    adminLimit: 5,
    remark: '',
  });
  showModal.value = true;
};

const handleEdit = (row: any) => {
  modalTitle.value = '编辑专家库';
  Object.assign(formData, row);
  showModal.value = true;
};

const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除专家库"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.success('删除成功');
      loadData();
    },
  });
};

const handleSubmit = () => {
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      setTimeout(() => {
        message.success(formData.id ? '更新成功' : '创建成功');
        showModal.value = false;
        submitLoading.value = false;
        loadData();
      }, 1000);
    }
  });
};

const handleAuth = (row: any) => {
  currentPool.value = row;
  showAuthModal.value = true;
  loadUserData();
};

const loadUserData = () => {
  userLoading.value = true;
  setTimeout(() => {
    userTableData.value = [
      {
        id: '1',
        name: '张三',
        employeeId: 'EMP001',
        department: '管理员',
        authTime: '2024-01-15 10:30:00',
        status: '已授权',
      },
      {
        id: '2',
        name: '李四',
        employeeId: 'EMP002',
        department: '普通用户',
        authTime: '2024-01-16 14:20:00',
        status: '已授权',
      },
    ];
    userLoading.value = false;
  }, 500);
};

const handleAddUser = () => {
  showAddUserModal.value = true;
  userSearchResults.value = [];
  selectedUser.value = null;
  selectedUserRole.value = '';
};

const handleUserSearch = (value: string) => {
  if (!value || value.length < 2) {
    userSearchResults.value = [];
    return;
  }
  
  userSearchLoading.value = true;
  // 模拟搜索API调用
  setTimeout(() => {
    // 模拟搜索结果
    userSearchResults.value = [
      {
        label: '张三-技术部-zhangsan001',
        value: {
          id: 'user1',
          name: '张三',
          department: '技术部',
          employeeId: 'zhangsan001'
        }
      },
      {
        label: '李四-研发部-lisi002',
        value: {
          id: 'user2',
          name: '李四',
          department: '研发部',
          employeeId: 'lisi002'
        }
      },
      {
        label: '王五-产品部-wangwu003',
        value: {
          id: 'user3',
          name: '王五',
          department: '产品部',
          employeeId: 'wangwu003'
        }
      }
    ];
    userSearchLoading.value = false;
  }, 500);
};

const handleConfirmAddUser = () => {
  if (!selectedUser.value) {
    message.warning('请选择用户');
    return;
  }
  
  if (!selectedUserRole.value) {
    message.warning('请选择用户角色');
    return;
  }
  
  // 检查用户是否已经存在
  const existingUser = userTableData.value.find(user => user.employeeId === selectedUser.value.employeeId);
  if (existingUser) {
    message.warning('该用户已存在');
    return;
  }
  
  // 添加用户到列表
  const newUser = {
    id: Date.now().toString(),
    name: selectedUser.value.name,
    employeeId: selectedUser.value.employeeId,
    department: selectedUserRole.value, // 使用选择的角色
    authTime: new Date().toLocaleString(),
    status: '已授权'
  };
  
  userTableData.value.push(newUser);
  message.success('添加用户成功');
  showAddUserModal.value = false;
};

const handleRemoveUser = (row: any) => {
  dialog.warning({
    title: '确认移除',
    content: `确定要移除用户"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.success('移除成功');
      loadUserData();
    },
  });
};



onMounted(() => {
  loadData();
});
</script>

<style scoped>
.n-layout-page-header {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style> 